package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Serve {
    private ServerSocket serverSocket;//总机
    //存放所有客户端的输出流(key：客户端的昵称 value：客户端的输出流)
    private Map<String, PrintWriter> allOut = new HashMap<>();

    public Serve(){
        try{
            System.out.println("正在启动服务器");
            serverSocket = new ServerSocket(6666);
            System.out.println("服务器启动完毕");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了");
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Serve serve = new Serve();
        serve.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;//记录客户端的IP地址
        private String nickName;//记录客户端的昵称
        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }


        public void run(){
            PrintWriter pw = null;
            try {
                //通过socket获取输入流用于读取客户端发来的消息
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                //通过socket获取输出流用于向客户端发送消息
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter ow = new OutputStreamWriter(os, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(ow);
                pw = new PrintWriter(bw,true);

                nickName = br.readLine();//读取客户端发来的昵称
                synchronized (allOut) {//想集合中添加元素需要添加同步机制，保证多个线程不能同时添加
                    allOut.put(nickName,pw);//将客户端的昵称和输出流存入map中
                }
                //sendMsgToAll("["+nickName+"]加入聊天室");
                sendMsgToAll("上线了，当前在线人数"+allOut.size());

                //读取客户端发来的消息
                String msg ;
                while ((msg = br.readLine()) != null){
                    //System.out.println("客户端说："+msg);//服务端输出客户端发送的消息
                    //pw.println("服务器说："+msg);//服务端回复客户端
                    if (msg.startsWith("@")){
                        sendMessageToSomeone(msg);
                    }else {
                        sendMsgToAll("说:" + msg);
                    }
                }
            } catch (IOException e) {

            } finally {
                synchronized (allOut) { //从集合中删除元素需要同步机制，保证多个线程不能同时删除
                    //根据昵称将map中的输出流删除
                    allOut.remove(nickName);
                }
                sendMsgToAll("下线了，当前在线人数"+allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        /**
         * 将消息发送给所有的客户端 实现群聊
         */
        private void sendMsgToAll(String msg){
            System.out.println(nickName+"["+host+"]"+msg);
            synchronized (allOut) {//群发时候需要同步，保证多个线程不能同时向客户端发送消息
                /*
                  新循环遍历集合就是迭代器，因为迭代器遍历过程中不能用集合的方式
                  增删元素，迭代器会报异常，为了保证正常遍历，所以需要加锁
                 */
                for (PrintWriter o : allOut.values()) {
                    o.println(nickName + "[" + host + "]" + msg);
                }
            }
        }

        private void sendMessageToSomeone(String msg){
            //message的格式：@昵称:内容
            if (msg.matches("@.+:.+")){
                //截取昵称 第一个@和第一个:之间的内容
                String toNickName = msg.substring(1,msg.indexOf(":"));
                if (allOut.containsKey(toNickName)){//判断在线
                    //获取toNickName的输出流
                    PrintWriter pw = allOut.get(toNickName);
                    //截取昵称后面的私聊内容
                    String toMsg = msg.substring(msg.indexOf(":")+1);
                    pw.println(nickName+"悄悄对你说："+toMsg);
                }else {//判断不在线
                    //获取当前客户端的输出流
                    PrintWriter pw = allOut.get(nickName);
                    pw.println("该用户["+toNickName+"]不在线");
                }
            }else {
                PrintWriter pw = allOut.get(nickName);
                pw.println("私聊格式不正确!");
            }
        }


    }
}
